package com.ficus.road.maintain.third.dk;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Optional;

/**
 * @author xiawen yang
 * @date 2022/7/8 上午11:27
 */
@Component
@Slf4j
public class BaseDK {

    private static final String DK_URL = "http://180.169.5.114:18081/protocol/proxy/request";
    private static final String ERR_MSG = "调用电科接口异常";
    protected String reqType;
    @Autowired
    private RestTemplate restTemplate;

    protected String getReqType() {
        return this.reqType;
    }

    public <T> Optional<T> getDKData(Class<T> clazz) {
        String reqType = getReqType();
        DKHttpRequest dkHttpRequest = new DKHttpRequest(reqType);
        HttpEntity<DKHttpRequest> httpEntity = new HttpEntity<>(dkHttpRequest);
        ResponseEntity<T> responseEntity = null;
        try {
            responseEntity = restTemplate.exchange(DK_URL, HttpMethod.POST, httpEntity, clazz);
        } catch (Exception e) {
            log.error(ERR_MSG, e);
            return Optional.empty();
        }
        return Optional.ofNullable(responseEntity.getBody());
    }

    @Data
    static class DKHttpRequest {
        @JsonProperty("req_type")
        private final String reqType;
        @JsonProperty("req_header")
        private DKHttpHeader reqHeader;

        public DKHttpRequest(String reqType) {
            this.reqType = reqType;
            this.reqHeader = DKHttpHeader.INSTANCE;
        }
    }

    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    public static class DKHttpHeader {
        public static final DKHttpHeader INSTANCE = new DKHttpHeader(
                "C12A7328-F81F-11D2-BA4B-00A0C93EC93B",
                "yitu001",
                "YTu#2022"
        );

        private String guid;

        private String user;

        private String pwd;
    }
}
